package com.bdth.weget.home.controller;

import com.bdth.weget.common.CommonResult;
import com.bdth.weget.home.entity.User;
import com.bdth.weget.home.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author LGP
 * @since 2018-11-08
 */
@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    @RequestMapping(value="/login", method = {RequestMethod.GET})
    public String login(){
        return "sys/login";
    }

    @RequestMapping(value="/doLogin", method = {RequestMethod.POST})
    @ResponseBody
    public CommonResult<User> doLogin(HttpServletRequest request, @RequestParam("username") String username, @RequestParam("password") String password){
        User bean = userService.doLogin(username,password);
        if(bean!=null) {
            request.getSession().setAttribute("loginUser",bean);
            request.getSession().setMaxInactiveInterval(36000);
            return new CommonResult<User>("200", "用户登录成功", bean);
        }
        return new CommonResult<User>("400","用户名或密码错误",null);
    }

    @RequestMapping(value = "/doLogout", method = {RequestMethod.GET})
    public String doLogout(HttpServletRequest request){
        request.getSession().setAttribute("loginUser",null);
        request.getSession().removeAttribute("loginUser");
        return "redirect:/login";
    }

}
